import React, { useState } from 'react';
import { Field } from '@formily/core';
import { useForm } from '@formily/react';
import { Select } from 'antd';
import tableApi from '../../preview/web/serviceApi';

const SortField = (props: any) => {
  const form = useForm();
  const [options, setOptions] = useState([]);
  const onSelect = (value: string) => {
    props.onChange(value);
  };
  const onMouseEnter = () => {
    const sortField: any = form.query('*.sortField').take() as Field;
    const columnConfig = form.query('*.columnConfig').take() as any;
    const modelKey = columnConfig.value?.queryFields?.find((field) => field?.Master)?.ModelKey;
    if (sortField.dataSource === undefined && modelKey) {
      const appId = form['appInfo']!.appId;
      tableApi.getManyFields(appId, modelKey).then((res) => {
        if (res) {
          const intFields =
            res[0].Fields.filter((field) => field.Type == 'int' || field.Type == 'bigInt') || [];
          const sortFieldOptions = intFields.map((field) => {
            return {
              label: field.Name,
              value: field.Name,
            };
          });
          sortField.setDataSource(sortFieldOptions);
          setOptions(sortFieldOptions);
        }
      });
    }
    if (!options?.length && sortField.dataSource) {
      setOptions(sortField.dataSource);
    }
  };
  return (
    <Select 
    showSearch
    filterOption={(input, option) =>
     (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
   }
    value={props.value} options={options} onMouseEnter={onMouseEnter} onSelect={onSelect} />
  );
};

export default SortField;
